import {StyleSheet, Text, TouchableOpacity, View, TextInput, Image, Clipboard} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcButton from "@/components/FcButton";
import FcModal from '@/components/FcModal';
import FormTitle from "@/components/FormTitle";
import FcTextInput from "@/components/FcTextInput";
import NoData from "@/components/NoData";
import useGetStorage from "@/hooks/useGetStorage";
import {Video} from 'expo-av';
import {Toast, Flex} from "@ant-design/react-native";
import {useDispatch, useSelector} from "react-redux";
import {set_rowData} from "@/store/reducer/contentManage/contentManageSlice";
import {router, useLocalSearchParams} from "expo-router";

import {
  useEditContentTextMutation,
  useGetTagListMutation,
  useAddGroupMutation,
  useEditGroupMutation,
  useBatchGroupingMutation,
  useGetAccountAssignListQuery,
  useDetectingSensitiveMutation,
  useGetGroupTemplateListQuery,
  useAddContentMutation,
  useDeleteProjectRelationMutation
} from "@/store/api/contentManage/contentManageApi";

import {
  useGetDeptTreeListQuery,
} from "@/store/api/login/loginApi";

type Props = {}

const detail = (props: Props) => {
  const [parentData, setParentData] = useState<any>({groupIds: []})
  const [contentT, setContentT] = useState('')
  const [contentC, setContentC] = useState('')
  const [contentP, setContentP] = useState('')
  const [isAIWork, setIsAIWork] = useState(false)
  const [groupOpen, setGroupOpen] = useState(false)
  const [addGroupOpen, setAddGroupOpen] = useState(false)
  const [groupName, setGroupName] = useState('')
  const [staffOpen, setStaffOpen] = useState(false)
  const [accountOpen, setAccountOpen] = useState(false)
  const [titleTextOpen, setTitleTextOpen] = useState(false)
  const [isDetection, setIsDetection] = useState(false);
  const [groupTemplateOpen, setGroupTemplateOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [tagList,setTagList] = useState<any>([])
  const [deptTreeList,setDeptTreeList] = useState<any>([])
  const [accountList,setAccountList] = useState<any>([])
  const [groupTemplateList,setGroupTemplateList] = useState<any>([])
  const [operationType, setOperationType] = useState<any>('')
  const [detectionData, setDetectionData] = useState<any>({})
  const [searchText, setSearchText] = useState<any>('')
  const [isShowAll, setIsShowAll] = useState(true);

  const [reg, setReg] = useState<any>(/^\s*【标题】[:：]?\s*(.*?)\s*【正文】[:：]?\s*(.*?)\s*【发布语】[:：]?\s*(.*?)\s*$/)

  const {data:deptListDataRef,isSuccess:deptListSuccess} = useGetDeptTreeListQuery({depType: 2})
  const {data:accountAssignListRef,isSuccess:accountAssignListSuccess} = useGetAccountAssignListQuery({})
  const {data:groupTemplateListRef,isSuccess:groupTemplateListSuccess} = useGetGroupTemplateListQuery({})

  const [editContentTextFun] = useEditContentTextMutation()
  const [getTagListFun] = useGetTagListMutation()
  const [addGroupFun] = useAddGroupMutation()
  const [editGroupFun] = useEditGroupMutation()
  const [batchGroupingFun] = useBatchGroupingMutation()
  const [detectingSensitiveFun] = useDetectingSensitiveMutation()
  const [addContentFun] = useAddContentMutation()
  const [deleteProjectRelationFun] = useDeleteProjectRelationMutation()
 
  const dispatch = useDispatch()
  const {type} = useLocalSearchParams()

  const header = (
    <TouchableOpacity style={{marginBottom: 20}}>
      <View style={styles.search_wrap}>
        <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 7}}>&#xe641;</Text>
        <TextInput 
          style={styles.search} 
          placeholder={'请输入要搜索内容'} 
          placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
          onChangeText={(val) => setSearchText(val)}
          value={searchText}
        />
      </View>
    </TouchableOpacity>
  )

  let p = useSelector(state => state.contentManage.rowData)
  
  useEffect(() => {
    console.log(p, 'ppppppppp')

    if(type == 'add'){
      setIsAIWork(true)
    }else{
      if(p) setParentData(p)

      let flag = reg.test(p.content)
      setIsAIWork(flag)
      setContentT(flag ? p.content.split(/【标题】[:：]/)[1].split(/【正文】[:：]/)[0].trim() : '')
      setContentC(flag ? p.content.split(/【正文】[:：]/)[1].split(/【发布语】[:：]/)[0].trim() : p.content)
      setContentP(flag ? p.content.split(/【发布语】[:：]/)[1].trim() : '')

      if(p.videoUrl){
        setIsShowAll(false)
      }else{
        setIsShowAll(true)
      }
    }

    if(deptListDataRef?.code === 0){
      let list = deptListDataRef?.result || []
      let arr:any = []

      list.forEach((main:any) => {
        forEachEmpList(main, arr);
      })
      setDeptTreeList(arr)
    }

    if(accountAssignListRef?.code === 200){
      let list = accountAssignListRef?.result || []
      setAccountList(list)
    }

    if(groupTemplateListRef?.code === 200){
      let list = groupTemplateListRef?.result[0].list || []
      setGroupTemplateList(list)
    }
    
    getTagList()

    setOperationType(type)
    
  }, [type, deptListDataRef, deptListSuccess, accountAssignListRef, accountAssignListSuccess, groupTemplateListRef, groupTemplateListSuccess, p])

  //获取组件架构
  const forEachEmpList = (obj:any, arr:any) => {
    obj.empList.forEach((user:any) => {
      arr.push({label:user.realname,value:user.realname,key:user.id});
    })
    if(obj.children && obj.children.length > 0) {
      obj.children.forEach((child:any) => {
        forEachEmpList(child, arr);
      })
    }
  }

  // 获取标签列表
  const getTagList = () => {
    getTagListFun({}).then(res => {
      if(res.data.code === 200){
        setTagList(res.data.result.records)
      }
    })
  }

  // 复制文案
  const handleCopyText = async(val:any) => {
    try {
      await Clipboard.setString(val);
      Toast.info('复制成功')
    } catch (error) {
      Toast.info('复制失败')
    }
  }

  //修改文案
  const blurTextInput = () => {
    if(operationType == 'add') return

    let str = isAIWork ? ('【标题】:' + contentT + '【正文】:' + contentC + '【发布语】:' + contentP) : contentC;

    let params = {
      id:parentData.id,
      createBy: parentData.createBy || '',
      createUsername: parentData.createUsername || '',
      content:str
    }
    editContentTextFun(params).then(res => {
      if (res.data.code === 200) {
        Toast.info('编辑成功')

        let obj = {
          ...parentData,
          content: str
        }
        dispatch(set_rowData(obj))
      }
    })
  }

  //选择标签change
  const handleCheckChange = (index:any) => {
    let arr = JSON.parse(JSON.stringify(tagList))
    arr[index].checked = !arr[index].checked
    setTagList(arr)
  }

  // 打开分组弹窗
  const handleGroupOpen = (item:any) => {
    setAddGroupOpen(true)
    setGroupName(item ? item.name : '')
    setParentData({...parentData, tagId: item ? item.id : null})
  }

  // 新增分组
  const handleAddGroup = () => {
    if(parentData.tagId){
      editGroupFun({id: parentData.tagId, name: groupName}).then(res => {
        if (res.data.code === 200) {
          Toast.info('编辑成功')
          getTagList()
        }
      })
    }else{
      addGroupFun({id: null, name: groupName}).then(res => {
        if (res.data.code === 200) {
          Toast.info('新增成功')
          getTagList()
        }
      })
    }
  }

  // 选择分组确定
  const handlecheckGroup = () => {
    let arr = tagList.filter((item: any) => item.checked).map((item: any) => item.id)

    if(arr.length == 0) return

    if(operationType == 'add'){
      setParentData({
        ...parentData,
        groupIds: arr
      })
      setGroupOpen(false)
    }else{
      batchGroupingFun({ids: [parentData.id], groupIds: arr}).then(res => {
        if (res.data.code === 200) {
          Toast.info('分组成功')
          setGroupOpen(false)
  
          let obj = {
            ...parentData,
            groupIds: arr
          }
          dispatch(set_rowData(obj))
        }
      })
    }
  }

  const handleSubmitContent = (type:any, item:any) => {
    let params:any = {
      id: parentData.id
    }

    if(operationType == 'add'){
      if(type == 'staff'){
        setParentData({
          ...parentData,
          createBy: item.key,
          createUsername: item.value,
        })
      }else if(type == 'account'){
        setParentData({
          ...parentData,
          assignContent: item.accountId,
          assignType: 0,
          pubType: item.sourcePlatform == 'kuaishou' ? 1 : item.douyinOrgAccount ? 2 : 0,
        })
      }else if(type == 'groupTemplate'){
        setParentData({
          ...parentData,
          templateName: item.name,
          templateId: item.id,
        })
      }
    }else{
      if(type == 'staff'){
        params.createBy = item.key || ''
        params.createUsername = item.value || ''
      }else if(type == 'account'){
        params.assignContent = item.accountId
        params.assignType = 0
        params.pubType = item.sourcePlatform == 'kuaishou' ? 1 : item.douyinOrgAccount ? 2 : 0
      }else if(type == 'remark'){
        params.remark = parentData.remark
      }
  
      editContentTextFun(params).then(res => {
        if (res.data.code === 200) {
          Toast.info('编辑成功')
          
          let obj = {
            ...parentData,
            ...params
          }
  
          dispatch(set_rowData(obj))
        }
      })
    }
  }

  //生成发布语
  const handleGenerateTitle = async() => {
    Toast.config({ duration: 0})
    let loading:any = null
    setTimeout(() => {
      loading = Toast.loading('发布语生成中')
    }, 100)

    await useGetStorage('token').then(async (token) => {
      try {
        const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}mm/mmContentManagePub/createTitle?id=${parentData.id}`,{
          method: 'POST',
          headers: {
            'content-type': 'application/json',
            'x-access-token': token,
          },
        });

        const blob = await response.blob();
        const reader = new FileReader();

        reader.onload = (event:any) => {
          const result = event.target.result;
          // 按行分割流式数据
          const lines = result.split('\n');
          lines.forEach((line:any) => {
            if (line) {
              let newLine = `${line.replace('data:','')}`;
              // 在这里处理流式数据
              let res = JSON.parse(newLine)
              if (res.status == 'success') {
                let txt = res.text.replace(/(<br\/>)|(<br)/g, '');

                setParentData({
                  ...parentData,
                  title: res.text,
                  titleList: splitTitle(txt)
                })

                if(res.stop){
                  Toast.remove(loading)
                  Toast.config({ duration: 2})
                  Toast.info('发布语生成成功')
                }
              }
            }
          });
        };

        reader.onerror = (error) => {
          console.error('Error reading blob:', error);
        };

        reader.readAsText(blob);
      }catch (error) {
        Toast.remove(loading)
        Toast.config({ duration: 2})
      }
    })
  }

  //采纳发布语
  const handleAdopt = (val:any) => {
    setParentData({
      ...parentData,
      pubTitleIndex: val,
    })
  }

  const splitTitle = (text:any) => {
    if(!text) return [];
    text = text.replace(/[\r\n]+/,'');
    try {
      const arr = JSON.parse('['+text+']');
      return arr;
    }
    catch {
      try {
        return JSON.parse('["'+text+'"]');
      }
      catch {
        return []
      }
    }
  }

  //脱敏检测
  const detectingContent = () => {
    Toast.config({ duration: 0})
    let loading:any = null
    setTimeout(() => {
      loading = Toast.loading('脱敏检测中')
    }, 100)
    detectingSensitiveFun({id: parentData.id}).then(res => {
      if(res.data.code == 200){
        setIsDetection(true)
        setDetectionData(JSON.parse(res.data.result))
        Toast.remove(loading)
        Toast.config({ duration: 2})
        Toast.info('检测成功')
      }
    })
  }

  //新增文案
  const handleAddContent = () => {
    if(isVerification()) return

    let params = {
      content: '【标题】:' + contentT + '【正文】:' + contentC + '【发布语】:' + contentP,
      ...parentData
    }

    addContentFun(params).then(res => {
      if(res.data.code == 200){
        Toast.info('新增成功')
        dispatch(set_rowData(params))
        router.back()
      }
    })
  }

  //下载视频
  const downloadVideo = () => {
    let xhr = new XMLHttpRequest();
      xhr.open("GET", parentData.videoUrl, true);
      xhr.responseType = "blob";
      xhr.onload = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          let a = document.createElement("a");
          a.href = window.URL.createObjectURL(new Blob([xhr.response], { type: 'video/mp4' }));
          a.download = 'download';
          document.body.appendChild(a);
          a.click();
          a.remove();
        }
      };
      xhr.send();
  }

  //删除视频
  const handleDeleteVideo = () => {
    if(parentData.pubStatus == 1 || parentData.pubStatus == 3 ) return Toast.info('当前状态不可操作')

    deleteProjectRelationFun({id: parentData.id}).then(res => {
      if(res.data.code == 200){
        Toast.info('删除成功')
        let obj = {
          ...parentData,
          videoUrl: ''
        }
        dispatch(set_rowData(obj))
      }
    })
  }

  //校验内容
  const isVerification = () => {
    if(operationType == 'add'){
      if(!contentT || !contentC || !contentP || !parentData.templateName || !parentData.createUsername){
        return true
      }
    }else{
      if(!contentT || !contentC || !contentP || parentData.groupIds.length == 0 || !parentData.createUsername || !parentData.assignContent){
        return true
      }
    }

    return false
  }

  return (
    <PageScrollView
      isTransparentTab
      pageTab={
        <PageTabBar
          style={{marginVertical: 10}}
          title={operationType === 'add' ? '新增文案' : '详情'}
        />
      }
      pageBottom = {
        operationType === 'add' ? 

        <View style={[styles.flex_between, {height: 56, paddingHorizontal: 16, backgroundColor: '#FFF'}]}>
          <FcButton
            onPress={() => router.back()}
            type='default'
            style={{width: '48%', height: 40, justifyContent: 'center'}}
            itemStyle={{width: '100%', height: '100%', borderRadius: 8, backgroundColor: '#F1F2F4'}}
            textName='取消'
          ></FcButton>
          <FcButton
            onClick={() => handleAddContent()}
            type='BjJB'
            colors={!isVerification() ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
            style={{width: '48%', height: 40, justifyContent: 'center'}}
            itemStyle={{borderRadius: 8, fontSize: 15}}
            textName='确定'
          />
        </View>
        :
        !parentData.videoUrl ?
        <View style={[styles.flex_between, {height: 56, paddingHorizontal: 16, backgroundColor: '#FFF'}]}>
          <FcButton
            onPress={() => detectingContent()}
            type='default'
            style={{width: '48%', height: 40, justifyContent: 'center'}}
            itemStyle={{width: '100%', height: '100%', borderRadius: 8, backgroundColor: '#F1F2F4'}}
            textName='内容脱敏检测'
          ></FcButton>
          <FcButton
            onClick={() => {}}
            type='BjJB'
            colors={!isVerification() ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
            style={{width: '48%', height: 40, justifyContent: 'center'}}
            itemStyle={{borderRadius: 8, fontSize: 15}}
            textName='AI成片'
          />
        </View>
        : !parentData.pubStatus ?
        <View style={[styles.flex_between, {height: 56, paddingHorizontal: 16, backgroundColor: '#FFF'}]}>
          <FcButton
            onPress={() => {}}
            type='default'
            style={{width: '48%', height: 40, justifyContent: 'center'}}
            itemStyle={{width: '100%', height: '100%', borderRadius: 8, backgroundColor: '#F1F2F4'}}
            textName='再次成片'
          ></FcButton>
          <FcButton
            onClick={() => router.push('/videoPublish?type=contentManage')}
            type='BjJB'
            colors={!isVerification() ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
            style={{width: '48%', height: 40, justifyContent: 'center'}}
            itemStyle={{borderRadius: 8, fontSize: 15}}
            textName='发布视频'
          />
        </View>
        : null
      }
    >
      <View>
        <View style={{backgroundColor: '#FFF', padding: 12, borderRadius: 8}}>
          <Flex>
            {
              operationType === 'add' ?
              <FormTitle 
                isLeftIcon 
                title='AI文案' 
                style={{paddingVertical: 0}} 
                titleHintStyle={{color: '#F56567', fontSize: 16, marginLeft: 5}}
                titleHint={'*'}
              />
              :
              <FormTitle isLeftIcon  title='AI文案'  style={{paddingVertical: 0, flex: 1}} />
            }
            
            {operationType !== 'add' && <TouchableOpacity onPress={() => handleCopyText(parentData.content)}>
              <Flex style={styles.copy_btn} justify='center'>
                <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: '#000'}}>&#xe65e;</Text>
                <Text style={{fontSize: 12}}>复制</Text>
              </Flex>
            </TouchableOpacity>}
          </Flex>

          {
            isAIWork ? 
            <View style={{position: 'relative', marginTop: 5}}>
              <TextInput
                style={[styles.content_input, {height: 120}]}
                multiline={true}
                value={contentT}
                placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
                placeholder={'请输入标题'}
                onChangeText={(val) => setContentT(val)}
                onBlur={blurTextInput}
              />
              <Text style={[styles.input_title, {backgroundColor: 'rgba(255, 157, 0, 0.2)', color: '#FF9D00'}]}>标题</Text>
            </View>
            : null
          }
          <View style={{position: 'relative', marginVertical: 15}}>
            <TextInput
              style={[styles.content_input, {height: 120}]}
              multiline={true}
              value={contentC}
              placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
              placeholder={'请输入内容'}
              onChangeText={(val) => setContentC(val)}
              onBlur={blurTextInput}
            />
            <Text style={[styles.input_title, {backgroundColor: 'rgba(41, 204, 160, 0.2)', color: '#29CCA0'}]}>{isAIWork ? '正文' : '文案内容'}</Text>
          </View>
          {
            isAIWork ? 
            <View style={{position: 'relative'}}>
              <TextInput
                style={[styles.content_input, {height: 120, paddingBottom: 36}]}
                multiline={true}
                value={contentP}
                placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
                placeholder={'请输入发布语'}
                onChangeText={(val) => setContentP(val)}
                onBlur={blurTextInput}
              />
              <Text style={[styles.input_title, {backgroundColor: 'rgba(40, 86, 255, 0.2)', color: '#2856FF'}]}>发布语</Text>
              <FcButton
                onClick={() => {setTitleTextOpen(true); handleGenerateTitle()}}
                type='BjJB'
                colors={['#6989FF', '#C65EFD']}
                style={styles.write_btn}
                itemStyle={{borderRadius: 8, fontSize: 12}}
                textName={'AI编写'}
                btnLeftEle={
                  <Text style={{
                    fontFamily: 'FcIconFont',
                    fontSize: 16,
                    color: 'white'
                  }}>&#xe63d;</Text>
                }
              />
            </View>
            : null
          }
          {
            isShowAll ?
            <View>
              {
                operationType == 'add' ? 
                <View>
                  <FormTitle 
                    style={{paddingTop: 16, paddingBottom: 8}} 
                    title='文案类型'
                    titleHintStyle={{color: '#F56567', fontSize: 16, marginLeft: 5}}
                    titleHint={'*'}
                  />
                  
                  <TouchableOpacity onPress={() => {setGroupTemplateOpen(true)}}>
                    <View style={styles.item_wrap}>
                      <Text style={[parentData.templateName ? styles.item_label : styles.item_hint]}>
                        {parentData.templateName || '请选择'}
                      </Text>
                      <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: '#79797A'}}>&#xe609;</Text>
                    </View>
                  </TouchableOpacity>
                </View>
                : null
              }

              {
                operationType === 'add' ?
                <FormTitle 
                  title='编写人员' 
                  style={{paddingTop: 16, paddingBottom: 8}}
                  titleHintStyle={{color: '#F56567', fontSize: 16, marginLeft: 5}}
                  titleHint={'*'}
                />
                :
                <FormTitle style={{paddingTop: 16, paddingBottom: 8}} title='编写人员'/>
              }
              <TouchableOpacity onPress={() => setStaffOpen(true)}>
                <View style={styles.item_wrap}>
                  <Text style={[parentData.createUsername ? styles.item_label : styles.item_hint]}>{parentData.createUsername || '请选择'}</Text>
                  <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: '#79797A'}}>&#xe609;</Text>
                </View>
              </TouchableOpacity>
              
              <FormTitle style={{paddingTop: 16, paddingBottom: 8}} title='分组标签'/>
              <TouchableOpacity onPress={() => {setGroupOpen(true)}}>
                <View style={styles.item_wrap}>
                  <Text style={[tagList.filter((item:any) => parentData.groupIds.includes(item.id)).map((item:any) => item.name).join() ? styles.item_label : styles.item_hint]}>
                    {tagList.filter((item:any) => parentData.groupIds.includes(item.id)).map((item:any) => item.name).join() || '请选择'}
                  </Text>
                  <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: '#79797A'}}>&#xe609;</Text>
                </View>
              </TouchableOpacity>
    
              <FormTitle style={{paddingTop: 16, paddingBottom: 8}} title='备注'/>
              <TextInput
                style={[styles.content_input, {height: 56, lineHeight: 20}]}
                multiline={true}
                value={parentData.remark}
                placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
                placeholder={'请输入备注'}
                onChangeText={(val) => setParentData({...parentData, remark: val})}
                onBlur={() => handleSubmitContent('remark', {})}
              />
    
              <FormTitle style={{paddingTop: 16, paddingBottom: 8}} title='视频分配'/>
              <TouchableOpacity onPress={() => {setAccountOpen(true)}}>
                <View style={styles.item_wrap}>
                  <Text style={[accountList.find((item:any) => parentData.assignContent == item.accountId)?.nickname ? styles.item_label : styles.item_hint]}>
                    {accountList.find((item:any) => parentData.assignContent == item.accountId)?.nickname || '请选择'}
                    </Text>
                  <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: '#79797A'}}>&#xe609;</Text>
                </View>
              </TouchableOpacity>
            </View>
            : 
            <TouchableOpacity style={[styles.flex_center, {marginVertical: 20}]} onPress={() => {setIsShowAll(!isShowAll)}}>
              <Text style={{color: 'rgba(0, 0, 0, 0.5)', marginRight: 5}}>显示全部</Text>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: 'rgba(0, 0, 0, 0.5)'}}>&#xe600;</Text>
            </TouchableOpacity>
          }

        </View>

        {
          parentData.videoUrl != null ? (
          <View style={{backgroundColor: '#FFF', padding: 12, borderRadius: 8, marginTop: 10}}>

              <FormTitle 
                isLeftIcon
                title='视频预览'
                style={{paddingTop: 0, paddingBottom: 8}}
                right={
                  <Flex>
                    <TouchableOpacity style={{marginRight: 15}} onPress={() => downloadVideo()}>
                      <Text style={{fontFamily: 'FcIconFont', fontSize: 18, color: '#000'}}>&#xe666;</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => setDeleteOpen(true)}>
                      <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: '#000'}}>&#xe61d;</Text>
                    </TouchableOpacity>
                  </Flex>
                }
              />

            <View style={{width: '100%', height: 300}}>
              <Video
                style={{ width: '100%', height: '100%' }}
                source={{ uri: parentData.videoUrl }} // 视频 URL
                useNativeControls
                resizeMode="contain"
                isLooping={false}
              />
            </View>
          </View>
          ) : null
        }


        {/* 分组弹窗 */}
        <FcModal
          isOpen={groupOpen}
          onFcModalClose={() => setGroupOpen(false)}
          titleText='选择分组'
          titleBottomBorderWidth={1}
          bottom={
            <View style={styles.modal_bottom}>
              <TouchableOpacity style={{flexDirection: 'row',alignItems:'center'}} onPress={() => handleGroupOpen(null)}>
                <Text style={{fontFamily: 'FcIconFont', fontSize: 22, color: '#2856FF'}}>&#xe643;</Text>
                <Text style={{color: '#2856FF', marginLeft: 5}}>新增分组</Text>
              </TouchableOpacity>
                
              <FcButton
                onClick={() => handlecheckGroup()}
                type='BjJB'
                colors={tagList.filter((val:any) => val.checked).length > 0 ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
                style={{width: 88, height: 32, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 15}}
                textName='确定'
              />
            </View>
          }
        >
          <View>
            {tagList.map((item:any, index:any) => (
              <View key={index} style={[styles.modal_item_text, {display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}]}>
                <View style={styles.flex}>
                  <TouchableOpacity style={[styles.select_icon, item.checked && styles.select_active]} onPress={() => handleCheckChange(index)}>
                    {item.checked && <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                  </TouchableOpacity>
                  <Text style={{fontSize: 15}}>{item.name}</Text>
                </View>

                {/* <TouchableOpacity onPress={() => handleGroupOpen(item)}>
                  <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000'}}>&#xe630;</Text>
                </TouchableOpacity> */}
              </View>
            ))}

            {tagList.length == 0 && <View style={{flexDirection: 'column',alignItems: 'center',justifyContent: 'center',paddingTop: 60,paddingBottom: 120}}>
              <NoData hintText='暂无数据'/>
            </View>}
          </View>
        </FcModal>
        
        {/* 新增/编辑分组弹窗 */}
        <FcModal
          isOpen={addGroupOpen}
          transparent
          closeShow={false}
          animationType='fade'
          onFcModalClose={() => setAddGroupOpen(false)}
          style={{width: 280, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
          titleText={parentData.tagId ? '编辑产品' : '新增产品'}
          titleBottomBorderWidth={0}
          footer={[
            {
              text: '取消',
              onPress: () => setAddGroupOpen(false),
              style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
            },
            {
              text: '确认',
              onPress: () => handleAddGroup(),
              style: { color: '#2856FF',fontSize: 17 },
            },
          ]}
        >
          <View style={{paddingBottom: 20}}>
            <FcTextInput 
              multiline 
              text={groupName} 
              placeholder={'请输入产品名称'}
              onChangeText={setGroupName}
              height={45}
            />
          </View>
        </FcModal>

        {/* 编写人员弹窗 */}
        <FcModal
          isOpen={staffOpen}
          onFcModalClose={() => setStaffOpen(false)}
          titleText='编写人员'
          header={header}
          titleBottomBorderWidth={0}
        >
          <View style={{backgroundColor: '#F1F2F4', paddingHorizontal: 16}}>
            {
              deptTreeList.filter((val:any) => val.value.includes(searchText)).length == 0 ?
              <View style={{flexDirection: 'column',alignItems: 'center',justifyContent: 'center',paddingTop: 60,paddingBottom: 120}}>
                <NoData hintText='暂无数据'/>
              </View>
              :
              deptTreeList.filter((val:any) => val.value.includes(searchText)).map((item:any, index:any) => (
                <View key={index} style={[styles.flex_between, styles.staff_item]}>
                  <View style={styles.flex}>
                    {/* <Image style={{borderRadius: '50%', marginRight: 10}} source={require('@/assets/images/index/gw_icon.png')} resizeMode={'contain'}></Image> */}
                    <Text>{ item.value }</Text>
                  </View>
  
                  <FcButton
                    onClick={() => {handleSubmitContent('staff', item); setStaffOpen(false)}}
                    type={parentData.createUsername === item.value ? 'BjJB' : 'default'}
                    colors={['#6989FF', '#C65EFD']}
                    style={{width: 72, height: 32, justifyContent: 'center'}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8, fontSize: 15, textAlign: 'center', lineHeight: 32}}
                    textName={parentData.createUsername === item.value ? '已选择' : '选择'}
                    borderWidth={1}
                  />
                </View>
              ))
            }
          </View>
        </FcModal>

        {/* 视频分配弹窗 */}
        <FcModal
          isOpen={accountOpen}
          onFcModalClose={() => setAccountOpen(false)}
          titleText='视频分配'
          header={header}
          titleBottomBorderWidth={0}
        >
          <View style={{backgroundColor: '#F1F2F4', paddingHorizontal: 16}}>
            {
              accountList.filter((val:any) => val.nickname.includes(searchText)).length == 0 ?
              <View style={{flexDirection: 'column',alignItems: 'center',justifyContent: 'center',paddingTop: 60,paddingBottom: 120}}>
                <NoData hintText='暂无数据'/>
              </View>
              :
              accountList.filter((val:any) => val.nickname.includes(searchText)).map((item:any, index:any) => (
                <View key={index} style={[styles.flex_between, styles.staff_item]}>
                  <View style={styles.flex}>
                    <Image style={{width: 48,height: 48, borderRadius: '50%', marginRight: 10}} source={{uri: item.avatar}} resizeMode={'contain'}></Image>
                    <Text>{ item.nickname }</Text>
                  </View>

                  <FcButton
                    onClick={() => {handleSubmitContent('account', item); setAccountOpen(false)}}
                    type={parentData.assignContent === item.accountId ? 'BjJB' : 'default'}
                    colors={['#6989FF', '#C65EFD']}
                    style={{width: 72, height: 32, justifyContent: 'center'}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8, fontSize: 15, textAlign: 'center', lineHeight: 32}}
                    textName={parentData.assignContent === item.accountId ? '已选择' : '选择'}
                    borderWidth={1}
                  />
                </View>
              ))
            }
          </View>
        </FcModal>

        {/* 文案类型 */}
        <FcModal
          isOpen={groupTemplateOpen}
          onFcModalClose={() => setGroupTemplateOpen(false)}
          titleText='文案类型'
          titleBottomBorderWidth={1}
        >
          <View>
            {
              groupTemplateList.filter((val:any) => val.name.includes(searchText)).length == 0 ?
              <View style={{flexDirection: 'column',alignItems: 'center',justifyContent: 'center',paddingTop: 60,paddingBottom: 120}}>
                <NoData hintText='暂无数据'/>
              </View>
              :
              groupTemplateList.filter((val:any) => val.name.includes(searchText)).map((item:any, index:any) => (
                <TouchableOpacity key={index} style={[styles.modal_item_text]} onPress={() => {handleSubmitContent('groupTemplate', item); setGroupTemplateOpen(false)}}>
                  <Text style={{fontSize: 15, color: parentData.templateName === item.name ? '#2856FF' : ''}}>{item.name}</Text>
                </TouchableOpacity>
              ))
            }
          </View>
        </FcModal>

        {/* 发布语弹窗 */}
        <FcModal
          isOpen={titleTextOpen} 
          onFcModalClose={() => setTitleTextOpen(false)}
          titleText='AI发布语'
          titleBottomBorderWidth={1}
          titleRight={
            <Flex style={{height: '100%'}}>
              <FcButton
                onClick={() => handleGenerateTitle()}
                type='BjJB'
                colors={['#6989FF', '#C65EFD']}
                style={{width: 72, height: 28}}
                itemStyle={{borderRadius: 8}}
                textName='再次生成'
                borderWidth={1}
              />
            </Flex>
          }
        >
          <View style={{padding: 16}}>
            <View style={{marginBottom: 16}}>
              <View style={styles.title_text_item}>
                <FormTitle isLeftIcon title='发布语1' style={{paddingVertical: 0, flex: 1}} />
                <FcButton
                  onPress={() => handleAdopt(0)}
                  type={parentData.pubTitleIndex == 0 ? 'txtJBAndBkJB' : 'default'}
                  style={{width: 60, height: 28}}
                  itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                  textName={parentData.pubTitleIndex == 0 ? '已采纳' : '采纳'}
                  borderWidth={1}
                ></FcButton>
              </View>

              <FcTextInput
                style={{marginTop: 8}}
                text={parentData.titleList?.[0]}
                multiline
                height={120}
                placeholder={'输入发布语1'}
              />
            </View>

            <View style={{marginBottom: 16}}>
              <View style={styles.title_text_item}>
              <FormTitle isLeftIcon title='发布语2' style={{paddingVertical: 0, flex: 1}} />
                <FcButton
                  onPress={() => handleAdopt(1)}
                  type={parentData.pubTitleIndex == 1 ? 'txtJBAndBkJB' : 'default'}
                  style={{width: 60, height: 28}}
                  itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                  textName={parentData.pubTitleIndex == 1 ? '已采纳' : '采纳'}
                  borderWidth={1}
                ></FcButton>
              </View>

              <FcTextInput
                style={{marginTop: 8}}
                text={parentData.titleList?.[1]}
                multiline
                height={120}
                placeholder={'输入发布语2'}
              />
            </View>

            <View>
              <View style={styles.title_text_item}>
              <FormTitle isLeftIcon title='发布语3' style={{paddingVertical: 0, flex: 1}} />
                <FcButton
                  onPress={() => handleAdopt(2)}
                  type={parentData.pubTitleIndex == 2 ? 'txtJBAndBkJB' : 'default'}
                  style={{width: 60, height: 28}}
                  itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                  textName={parentData.pubTitleIndex == 2 ? '已采纳' : '采纳'}
                  borderWidth={1}
                ></FcButton>
              </View>

              <FcTextInput
                style={{marginTop: 8}}
                text={parentData.titleList?.[2]}
                multiline
                height={120}
                placeholder={'输入发布语3'}
              />
            </View>
          </View>
        </FcModal>

        {/* 内容脱敏检测 */}
        <FcModal
          isOpen={isDetection}
          transparent
          closeShow={false}
          animationType='fade'
          onFcModalClose={() => setIsDetection(false)}
          style={styles.modal_default}
          titleText={'内容脱敏检测'}
          titleDesc={'预警提示，仅供参考'}
          titleBottomBorderWidth={0}
          footer={[
            {
              text: '取消',
              onPress: () => setIsDetection(false),
              style: {color: 'rgba(0, 0, 0, 0.5)', fontSize: 17},
            },
            {
              text: '确定',
              onPress: () => setIsDetection(false),
              style: {color: '#2856FF', fontSize: 17},
            },
          ]}
        >
          <View style={{paddingBottom: 10}}>
            <Text style={styles.check_md}>
              <Text style={styles.check_md_txt}>脱敏检测目的：</Text>
              敏感词汇可能造成曝光了减少 、平台下架、用户投诉、版权纠纷、法律风险，请认真对待敏感内容检测结果，并对内容进行改善
            </Text>
            {!detectionData.sensitive &&
              <View style={[styles.check_hint, {paddingBottom: 10}]}>
                <Text style={[styles.check_hint_txt, {textAlign: 'center'}]}>没有发现违规风险！</Text>
              </View>
            }

            {detectionData.sensitive &&
              <>
                <View style={styles.check_hint}>
                  <Text style={styles.check_hint_txt}>{detectionData.riskAndAdviceSummary}</Text>
                </View>
                {detectionData?.sensitiveDetail?.map((item:any, index:any) =>
                  <View style={styles.check_hint} key={index}>
                    <Text style={styles.check_hint_txt}>{index + 1}.**<Text style={{color: '#FA5151'}}>{item.keyword}</Text>**</Text>
                    <Text style={styles.check_hint_txt}>**建议改进**：{item.advice}</Text>
                  </View>
                )}
              </>
            }
          </View>
        </FcModal>

        {/* 删除弹窗 */}
        <FcModal
          isOpen={deleteOpen}
          transparent
          closeShow={false}
          animationType='fade'
          onFcModalClose={() => setDeleteOpen(false)}
          style={{width: 280, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
          titleText={'确认要删除吗？'}
          titleBottomBorderWidth={0}
          footer={[
            {
              text: '取消',
              onPress: () => setDeleteOpen(false),
              style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
            },
            {
              text: '确认',
              onPress: () => handleDeleteVideo(),
              style: { color: '#2856FF',fontSize: 17 },
            },
          ]}
        >
          <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>一旦删除，当前视频将被删除哦~</Text>
        </FcModal>
      </View>
    </PageScrollView>
  )
}

export default detail

const styles = StyleSheet.create({
  content_input: {
    backgroundColor: '#F1F2F4',
    color: 'rgba(0,0,0,0.9)',
    fontSize: 15,
    lineHeight: 26,
    paddingTop: 20,
    paddingBottom: 8,
    paddingHorizontal: 12,
    borderRadius: 8,
    textAlignVertical: 'top',
  },
  input_title: {
    position: 'absolute',
    left: 0,
    top: 0,
    height: 18,
    fontSize: 12,
    lineHeight: 18,
    paddingHorizontal: 6,
    borderTopLeftRadius: 4,
    borderBottomRightRadius: 4
  },
  write_btn: {
    width: 75,
    height: 28,
    position: 'absolute',
    bottom: 8,
    right: 12,
  },
  flex_between: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  flex_center: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  flex: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
  },
  copy_btn: {
    width: 58,
    height: 28,
    borderRadius: 8,
    backgroundColor: '#F1F2F4',
  },
  item_wrap: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: 'space-between',
    height: 56,
    paddingHorizontal: 12,
    backgroundColor: '#F1F2F4',
    borderRadius: 8
  },
  item_label: {
    fontSize: 15,
    color: 'rgba(0,0,0,0.9)'
  },
  item_hint: {
    fontSize: 15,
    color: 'rgba(0,0,0,0.3)'
  },
  modal_bottom: {
    height: 56,
    display: 'flex',
    flexDirection: "row",
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
  },
  modal_item_text: {
    marginHorizontal: 16,
    height: 56,
    alignItems: 'center',
    justifyContent: 'center',
    borderBottomColor: 'rgba(0,0,0,0.05)',
    borderBottomWidth: 1,
    fontSize: 17,
    color: 'rgba(0,0,0,0.9)'
  },
  select_icon: {
    width: 20,
    height: 20,
    borderRadius: '50%',
    borderWidth: 1,
    borderColor: 'rgba(0,0,0,0.5)',
    marginRight: 8,
  },
  select_active: {
    borderColor: '#2856FF',
    backgroundColor: '#2856FF',
    flexDirection: 'row',
    alignItems: "center",
    justifyContent: "center"
  },
  search_wrap: {
    flexDirection: 'row',
    alignItems: "center",
    backgroundColor: '#F1F2F4',
    borderRadius: 9,
    marginHorizontal: 16,
    height: 40,
    
    paddingHorizontal: 14
  },
  search: {
    flex: 1,
    height: '100%',
    color: 'rgba(0,0,0,0.9)',
    lineHeight: 20,
  },
  staff_item: {
    height: 72,
    borderRadius: 8,
    marginTop: 10,
    paddingHorizontal: 12,
    backgroundColor: '#FFF',
  },
  title_text_item: {
    flexDirection: "row",
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  title_input: {
    backgroundColor: '#F1F2F4',
    color: 'rgba(0,0,0,0.9)',
    fontSize: 17,
    lineHeight: 26,
    borderRadius: 8,
    marginTop: 10,
    paddingVertical: 8,
    paddingHorizontal: 12,
  },
  modal_default: {
    width: 280,
    borderBottomRightRadius: 12,
    borderBottomLeftRadius: 12
  },
  check_md: {
    paddingHorizontal: 11,
    paddingVertical: 12,
    borderRadius: 8,
    color: 'rgba(0,0,0,0.9)',
    backgroundColor: '#F1F2F4',
    marginTop: 15,
    lineHeight: 18,
    fontSize: 12
  },
  check_md_txt: {
    color: '#FA5151'
  },
  check_hint: {
    marginTop: 12,
  },
  check_hint_txt: {
    lineHeight: 24,
    fontSize: 15,
    color: 'rgba(0,0,0,0.9)',
  },
  ai_btn: {
    width: 69,
    height: 28,
    position: "absolute",
    right: 16,
    bottom: 8
  },
})